<template>
  <div class="grid-page-background">   <!-- 单一根，指令才能生效，必须 v-modaldrag --->
  <div class="divide-line"></div>
  <el-row align="middle">
    <el-col :span="8"><div class="grid-title"><label>部门<!--功能名称--></label></div></el-col>
    <el-col :span="16"><div class="grid-title-tip"><!-- 功能描述 --></div></el-col>
  </el-row>
  <div class="divide-line">
  </div>
    <el-container :style="{backgroundColor:'#fff', height: mainHeight+'px'}">
        <el-aside width="300px" style="background-color:#fff; margin-right: 10px;">
          <DepartmentTree :height="mainHeight" :editable="true" :dragable="true" @departmentClick="onDepartmentChange"></DepartmentTree>
        </el-aside>
        <el-main>
<vxe-grid  v-bind="gridOptions.gridProps"  ref="employeeGrid"  @sortChange="($event:any)=>gridOptions.changeSort($event)">
    <template #toolbar_buttons>
      <el-space size="large">
      <query-field :filter-column="nameColumnFilter" @change="getEmployeeList"/> <!-- 姓名 查询条件 -->
      <query-field :filter-column="sexColumnFilter" @change="getEmployeeList"/> <!-- 性别 查询条件 -->
      <el-checkbox v-model="onlyDirectlyEmployee" border size="medium" @change="getEmployeeList">只看直属员工</el-checkbox>
      <el-space size="small">
      <el-button type="primary" @click="getEmployeeList" :icon="Search" size="medium">查询</el-button>
      <el-button @click="resetQueryFilters" :icon="Reset" size="medium">重置</el-button>
      <dayu-auth-button @click="addEmployeeBtnClick" :icon="Plus" size="medium" :authTag="actionState.authTag" :lockState="actionState.masterLockState" :masterLockState="actionState.masterLockState">新增</dayu-auth-button>
      </el-space>
      </el-space>
    </template>

    <template #top>
      <div class="grid-stats"><!-- 统计数据栏 -->
        <el-space>
          <InfoFilled twoToneColor="#1890FF" style="padding-left: 5px;"/>
          <span>共查询到 {{gridOptions.pager.totalRows}} 条记录</span>
          <div class="v-divider-w1" style="height:30px"></div>          
          <span>性别：</span>
          <span>记录条数：<el-tag color="#e62" style="color:#fff; font-weight: bold;">{{ statData.total.sexRowsCount || 0 }}</el-tag></span>        </el-space>
      </div>
    </template>
    <template #pager>
      <dayu-pager :pager="gridOptions.pager" @change="onPagerChange"></dayu-pager>
    </template>
    <template #sexColumn="{ row }">  <!-- 性别 字段自定义显示 -->
      <dayu-dropdown :row=row labelProp="sexCaption" valueProp="sex" :options="sexItems" @change="changeSex" :authTag="actionState.authTag" :lockState="row.rowLock" :masterLockState="actionState.masterLockState"></dayu-dropdown>
    </template>
    <template #operationColumn="{ row }">
      <el-space size="small" class="operationColumn">
        <el-button type="text" size="small" :auto-insert-space="false">附件</el-button>
        <el-button type="text" size="small" :auto-insert-space="false">详情</el-button>
        <dayu-auth-button @click="editEmployeeBtnClick(row.id)" type="primary" size="mini" :icon="Edit" plain :authTag="actionState.authTag" :lockState="row.rowLock" :masterLockState="actionState.masterLockState">编辑</dayu-auth-button>
        <dayu-auth-button @click="deleteEmployeeBtnClick(row.id, row.name)" type="danger" size="mini" :icon="Delete" plain :authTag="actionState.authTag" :lockState="row.rowLock" :masterLockState="actionState.masterLockState">删除</dayu-auth-button>
        <dayu-data-lock :onChangeState="employeeRowLockStateChange" size="mini" :dataId="row.id" :authTag="actionState.authTag" :masterLockState="actionState.masterLockState" v-model:lockState="row.rowLock"/>
      </el-space>
    </template>
  </vxe-grid>
        </el-main>
    </el-container>
  </div>

  <dayu-form-dialog title="员工-属性编辑" :formModal="employeeFormModal" :width="800" @ok='employeeFormModalHandleOk'>
    <EmployeeForm ref="employeeForm" :id="employeeFormModal.id" :departmentId="employeeFormModal.refId" :departmentName="employeeFormModal.refName" v-if="employeeFormModal.visible"/><!-- 增加v-if，每次弹窗会更新值 -->
  </dayu-form-dialog>

</template>

<script lang="ts" setup>

/*
 * @author: user
 * @date: 2021-11-25 16:55:15
 * @template: dayu-code-builder
*/

import { ref, reactive, onMounted, computed, watchEffect } from 'vue'
import { Search, Plus, Edit, Delete, Download as Export, InfoFilled, Refresh as Reset } from '@element-plus/icons';
import { ElMessage } from 'element-plus';
import { VxeGridProps } from 'vxe-table'
import store from '@/store'
import { FormModal, IForm } from '@/common/FormModal'
import { FilterValue, FilterColumn, FilterColumns, QueryConfig, ListBO, buildDefaultVxeGridOptions, myutil} from '@/common/dayu-common'
import { ActionState } from '@/common/AuthState'
import {mycolors} from '@/common/colors';
import DepartmentTree from './DepartmentTree.vue'
import EmployeeForm from './EmployeeForm.vue'
import { employeeService, EmployeeStats, EmployeeStatData } from '@/api/demo/EmployeeService';

/** 授权和锁定状态 */
const actionState = ref(new ActionState(true, true, 0xFFFF, 0, 0));

const employeeGrid = ref();
const employeeForm = ref();
const employeeFormModal = reactive(new FormModal());//表单弹窗

/**当前选中的树节点*/
const currDepartment = reactive({id:<number>NaN, name:''});
/**选中的树节点发生变化时的回调函数*/
function onDepartmentChange(department:any){
  if(department){
    currDepartment.id = department.id;
    currDepartment.name = department.name;
  }
  gridOptions.pager.pageIndex = 1;
  getEmployeeList();
}

//表格变量
const gridOptions = reactive(buildVxeGridOptions());//vxe-grid 的参数，包括表格数据
const aggregationData = reactive({aggregations:[]});//表格数据的统计值

//定义查询项
const nameColumnFilter = reactive(new FilterColumn('姓名', new FilterValue('name', 'string', 'like', false, false ), "")); // 姓名 
const sexColumnFilter = reactive(new FilterColumn('性别', new FilterValue('sex', 'string', 'equal', true, false ), "")); // 性别 
//查询项集合
const filterColumns = new FilterColumns([
    nameColumnFilter,
    sexColumnFilter
]);

const onlyDirectlyEmployee = ref(false);//只看直属员工

/** 整理统计数据 */
const statData = computed(() => {
  let statData_ = {
      total: new EmployeeStatData
      , sex_1:new EmployeeStatData, sex_2:new EmployeeStatData, sex_3:new EmployeeStatData};
  if(aggregationData.aggregations && aggregationData.aggregations.length > 0){
    for(let i=0; i<aggregationData.aggregations.length; i++){
      let row : EmployeeStats = aggregationData.aggregations[i] as EmployeeStats;
      if(row.aggregateGroupName == 'total'){
        statData_.total.sexRowsCount = row.sexRowsCount;
      }
      if(row.aggregateGroupName == 'sex'){
        if(row.sex == '1'){  //此处由模板自动生成，需要根据实际字典项的代码值进行修改。
          statData_.sex_1.sexRowsCount = row.sexRowsCount;
        }else if(row.sex == '2'){
          statData_.sex_2.sexRowsCount = row.sexRowsCount;
        }else if(row.sex == '3'){
           statData_.sex_3.sexRowsCount = row.sexRowsCount;
        }
      }
    }
  }
  return statData_;
});


/** 构造 vxe-grid 的参数 */
function buildVxeGridOptions(){
  let gridOptions = buildDefaultVxeGridOptions();//构造vxe-grid的默认属性
  let gridProps : VxeGridProps = { //本页面定制的属性
      border:"inner",
    columns: [
      { type: 'seq', title:'序号', width: 50, align:'center', fixed:'left'},
      { field: 'deptName', title: '所属部门',sortable:true, width: 100, align:'right'      ,showOverflow: true},
      { field: 'name', title: '姓名',sortable:true, width: 150, align:'left', fixed:'left'      ,showOverflow: true},
      { field: 'idCardType', title: '证件类型',sortable:true, width: 120, align:'left'      ,showOverflow: true},
      { field: 'idCardNumber', title: '身份证号',sortable:true, width: 150, align:'left'      ,showOverflow: true},
      { field: 'sex', title: '性别',sortable:true, width: 100, align:'center', slots:{default:'sexColumn'}      ,showOverflow: true},
      { field: 'birthday', title: '出生日期',sortable:true, width: 100, align:'center'      ,showOverflow: true},
      { field: 'birthplace', title: '籍贯',sortable:true, width: 150, align:'left'      ,showOverflow: true},
      { field: 'mobile', title: '电话',sortable:true, width: 150, align:'left'      ,showOverflow: true},
      { field: 'email', title: '邮箱',sortable:true, width: 150, align:'left'      ,showOverflow: true},
      { field: 'jobTitle', title: '岗位',sortable:true, width: 150, align:'left'      ,showOverflow: true},
      { field: 'education', title: '学历',sortable:true, width: 120, align:'left'      ,showOverflow: true},
      { field: 'school', title: '毕业学校',sortable:true, width: 150, align:'left'      ,showOverflow: true},
      { field: 'speciality', title: '专业',sortable:true, width: 150, align:'left'      ,showOverflow: true}
      ,{ title:'操作', width: 320, align:'center', slots:{default:'operationColumn'}, fixed:'right'}
    ]
  };
  gridOptions.pager.pageSize = 10;
  Object.assign(gridOptions.gridProps, gridProps);

  //排序事件的回调函数
  gridOptions.onSortChanged = function(field:string, order:string){
    console.log(`sort field:${field}, order:${order}`);
    getEmployeeList();
  }
  return gridOptions;
}

/** 分页组件事件回调（PageIndex或者PageSize发生变化时） */
const onPagerChange = (page: number, pageSize: number) =>{
  getEmployeeList();
}

/**从服务端获取数据（根据新的参数）*/
async function getEmployeeList(){
  if(!currDepartment.id)return; 
  gridOptions.gridProps.loading = true;//正在加载
  try{
    let response : any = await employeeService.getEmployeeExListAndStats(currDepartment.id, !onlyDirectlyEmployee.value, filterColumns.getQueryFilters(),
        new QueryConfig(gridOptions.pager.pageIndex, gridOptions.pager.pageSize, gridOptions.sorter.field, gridOptions.sorter.order));
    let listBO = response.data as ListBO;
    actionState.value.setActionState(listBO.authTag, listBO.lockState, listBO.lockState);
    gridOptions.gridProps.data = listBO.items;//表格数据
    aggregationData.aggregations = listBO.aggregations;
    let currPager:any = listBO.pager;
    gridOptions.gridProps.seqConfig = {startIndex: currPager.startRows};//重新设置行号的起始值
    gridOptions.pager.totalRows = currPager.totalRows as number;//重新设置总记录数
    if(!sexColumnFilter.codeItems){//第一次查询时，设置查询条件的下拉列表
      sexColumnFilter.codeItems = listBO.codeTypes["sex"];
    }
    sexItems.value = listBO.codeTypes["sex"];
  }finally{
    gridOptions.gridProps.loading = false;
  }
}

/** 重置查询条件 */
function resetQueryFilters(){
  filterColumns.reset();
  getEmployeeList();
}

/**cell编辑按钮点击事件*/
async function editEmployeeBtnClick(id : number) {
  employeeFormModal.showModal(id);//显示表单对话框
}


/**表单【确定】按钮点击事件*/
async function employeeFormModalHandleOk() {
  let response = await employeeFormModal.submit(employeeForm.value as IForm);
  console.log("after ok button clicked:");
  console.log(response);
  getEmployeeList();
}

/**cell上的删除按钮事件*/
async function deleteEmployeeBtnClick(id : number, name : string){
  myutil.confirmForDelete(`确认删除 ${name} 吗?`).then(async () => {
      await employeeService.deleteEmployee(id);
      getEmployeeList();
  });  
}


const sexItems = ref(new Array<{code:string, name:string}>());//字典值
async function changeSex(row:any, sex :any){//当通过下拉菜单更改性别时
  await employeeService.updateProp(row.id, "sex", sex);
 
  //let response : any = await employeeService.getEmployee(row.id);//如果此属性的改变，涉及到统计数据的改变，则需要注释掉此段代码，使用下面的getEmployeeList()调用。
  //let employee = response.data;
  //row.sex = employee.sex;
  //row.sexCaption = employee.sexCaption;
  getEmployeeList();//如果此属性的改变，涉及到统计数据的改变，则需要调用此函数，把上面的getEmployee函数注释掉。
}

async function employeeRowLockStateChange(id:number, lockState:number){
  try{
    let response = await employeeService.changeLockState(id, lockState);
    return Promise.resolve(lockState);
  }catch(ex:any){
    return Promise.reject(ex);
  }
}

/**添加按钮点击事件*/
async function addEmployeeBtnClick() {
  employeeFormModal.showModal(undefined, currDepartment.id, currDepartment.name);//显示表单对话框
}

/** 主区域的高度 */
const mainHeight = ref(800);
/** 监听浏览器窗口大小（监听vuex store里的值，在App.vue中监听window.size事件时会更改） */
watchEffect(() =>{
  mainHeight.value = store.state.windowClient.height - store.state.topBarHeight - store.state.bottomBarHeight - 80;
  gridOptions.gridProps.height = mainHeight.value - 20;
})

onMounted(() => {

});

</script>

<style scoped>

</style>